package cn.hfatec.shms.system.module.action;

import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.system.authData.model.AuthData;
import cn.hfatec.shms.system.authData.model.AuthDataParams;
import cn.hfatec.shms.system.authData.service.AuthDataService;
import cn.hfatec.shms.system.module.model.ModuleView;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Arrays;
import javax.annotation.Resource;


import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.system.module.model.ModuleParams;
import cn.hfatec.shms.system.module.model.Module;
import cn.hfatec.shms.system.module.service.ModuleService;
import cn.hfatec.shms.base.ShmsBaseAction;
import org.springframework.ui.Model;

import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/system/module")
public class ModuleAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "ModuleService")
    private ModuleService moduleService;

    @Resource(name = "AuthDataService")
    private AuthDataService authDataService;


    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(ModuleParams moduleParams, Page page, Model model) throws InvocationTargetException, IllegalAccessException {

        List<Module> allModuleList = moduleService.queryModuleTable(moduleParams);
        List MenuList = moduleService.getModuleList(ShmsConstant.ROOT_MODULE_ID, allModuleList);

        model.addAttribute("modulesTable", MenuList);
//        model.addAttribute("moduleParams", moduleParams);
        return "/system/module/list";
    }


    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(ModuleParams moduleParams, Page page, Model model) {
        try {
            list(moduleParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/module/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(String parentModuleId, Model model) {
        try {
            Module module = new Module();
            module.setParentModuleId(parentModuleId);
            model.addAttribute("module", module);
            boolean flag = false;


            //仅支持三层树
            if (ShmsConstant.ROOT_MODULE_ID.equals(parentModuleId)) {
                flag = true;
            } else {
                Module m = moduleService.queryModuleByModuleId(parentModuleId);
                if(ShmsConstant.ROOT_MODULE_ID.equals(m.getParentModuleId())){
                    flag = true;
                }else{
                    m = moduleService.queryModuleByModuleId(m.getParentModuleId());
                    if(ShmsConstant.ROOT_MODULE_ID.equals(m.getParentModuleId())){
                        flag = true;
                    }
                }

            }

            if(flag){
                return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/module/form", model)).toString();
            }else{
                return new JsonResponse<Map>(JsonResponse.RETURN_FAILURE, "新增失败，仅支持三层树状模块！", FreeMarkerUtil.render("/system/module/form", model)).toString();
            }



        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            Module module = moduleService.getModule(id);
            model.addAttribute("module", module);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/module/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteModule(Integer id, String moduleId) {
        try {
            ModuleParams moduleParams = new ModuleParams();
            List List = moduleService.queryModuleTable(moduleParams);
            List menuList = moduleService.getModuleList(moduleId, List);
            if (menuList.size() == 0) {

                AuthDataParams authDataParams = new AuthDataParams();
                authDataParams.setModuleId(moduleId);
                List authDataList = authDataService.queryAuthDataList(authDataParams);
                if(authDataList.size() !=0){
                    logger.error("请先删除属于该模块的权限，再删除该模块");
                    return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
                }
                moduleService.deleteModule(id, moduleId);
            } else {
                logger.error("请先删除子菜单，再删除该菜单！");
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + id + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveModule(@Valid Module module, BindingResult result) {

        try {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            moduleService.saveModule(module);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据Module保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 跳转到选择模块页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/goSelectModule")
    @ResponseBody
    public String goSelectModule(Model model) {

        try {
            List<ModuleView> allModuleList = moduleService.queryAllModuleList();
            model.addAttribute("modulesTable", allModuleList);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/module/selectModule", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
}
